﻿using Microsoft.EntityFrameworkCore;
using MyAspNetCoreTodo.Datas;
using MyAspNetCoreTodo.Dtos;
using MyAspNetCoreTodo.Identity;
using MyAspNetCoreTodo.Models;

namespace MyAspNetCoreTodo.Services
{
    public class TodoItemService : ITodoItemService
    {
        private readonly ApplicationDbContext _context;

        public TodoItemService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<bool> AddItemAsync(TodoItemDto newItem,ApplicationUser user)
        { 
            if (newItem.DueAt == null)
            {
                newItem.DueAt = DateTime.Now;
            }
            var entity = new TodoItem
            {
                Title = newItem.Title,
                DueAt = newItem.DueAt,
                IsDone = false
                ,
                UserId = user.Id
            };

            _context.Items.Add(entity);
            var result = await _context.SaveChangesAsync();
            return result > 0;
        }

        public async Task<IEnumerable<TodoItemDto>> GetIncompleteItemsAsync(ApplicationUser user)
        {
            var items = await _context.Items
                .Where(x => !x.IsDone && x.UserId== user.Id)
                .Select(x => new TodoItemDto
                {
                    Id = x.id,
                    IsDone = x.IsDone,
                    Title = x.Title,
                    DueAt = x.DueAt
                })
                .ToListAsync();

            return items;
        }

        public async Task<bool> MarkDoneAsync(Guid id, ApplicationUser user)
        {

            var item = await _context.Items.Where(t=>t.id==id&& t.UserId== user.Id).FirstOrDefaultAsync();
            if (item== null) 
            {
                return false;
            }

            item.IsDone = true;

            var saveResult = await _context.SaveChangesAsync();
            return saveResult == 1;
        }
    }
}
